/* global window */
import React from 'react'
import NProgress from 'nprogress'
import queryString from 'query-string'
import { routerRedux } from 'dva/router'
import pathToRegexp from 'path-to-regexp'
import { connect } from 'dva'
import { Layout, Loader } from 'components'
import { classnames,request, config } from 'utils'
import { Helmet } from 'react-helmet'
import { withRouter } from 'dva/router'
import '../themes/index.less'
import './index.less'
import { LocaleProvider } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';

const { prefix, openPages,api:{userState} } = config

const { Header, Bread, Footer, Sider, styles } = Layout
let lastHref

class App extends React.Component{
  constructor(props){
    super(props)
    this.heartbeatListener=null
  }
  heartbeat(){
 
    this.heartbeatListener=setTimeout(()=>{
  
      const token=sessionStorage.getItem("token")
      if(token){
        request({
          url: userState,
          method: 'get',
          data: {"selfHandleError":true},
        }).then(data=>{
          const {code}=data
          if(code==401||code==403){
            //清除token
            sessionStorage.removeItem("token")
            this.props.dispatch(routerRedux.push({
              pathname: '/login',
              search: queryString.stringify({
                  from: '/',
              }),
            }));
          }
        })
      }
      this.heartbeat() 

    },5000)
   
  }
  componentDidMount(){
    let baseUrl = "ws://127.0.0.1:12345";
     window.socket = new WebSocket(baseUrl);
     console.log('打开webSocket....')
    if(this.heartbeatListener){
      clearTimeout(this.heartbeatListener)
    }
    this.heartbeat()
  }
  componentWillUnmount(){

  }
  render(){
    const { children, dispatch, app, loading, location, history }=this.props
    const { user, siderFold, darkTheme, isNavbar, menuPopoverVisible, navOpenKeys, menu, permissions, orgList, currentOrg } = app
    let { pathname } = location;
    pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
    const { iconFontJS, iconFontCSS, logo } = config
    const current = menu.filter(item => pathToRegexp(item.route || '').exec(pathname))
    const hasPermission = current.length ? permissions.visit.includes(current[0].id) : false
    const href = window.location.href
    if (lastHref !== href) {
      NProgress.start()
      if (!loading.global) {
        NProgress.done()
        lastHref = href
      }
    }
    const headerProps = {
      menu,
      user,
      siderFold,
      isNavbar,
      menuPopoverVisible,
      navOpenKeys,
      orgList,
      currentOrg,
      setCurrentOrg(org) {
        dispatch({ type: 'app/setCurrentOrg', org })
          .then(res => history.replace(res.url))
      },
      switchMenuPopover() {
        dispatch({ type: 'app/switchMenuPopver' })
      },
      logout() {
        dispatch({ type: 'app/logout' })
      },
      switchSider() {
        dispatch({ type: 'app/switchSider' })
      },
      changeOpenKeys(openKeys) {
        dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } })
      },
      reSetPassWord(newPassWord, oldPassWord) {
        dispatch({ type: 'app/changePassWord', payload: { newPassword: newPassWord, password:oldPassWord} })
      }
    }

    const siderProps = {
      menu,
      siderFold,
      darkTheme,
      navOpenKeys,
      location,
      changeTheme() {
        dispatch({ type: 'app/switchTheme' })
      },
      changeOpenKeys(openKeys) {
        window.localStorage.setItem(`${prefix}navOpenKeys`, JSON.stringify(openKeys))
        dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } })
      },
    }

    const breadProps = {
      menu,
    }
    if (openPages && openPages.includes(pathname)) {
      return (<div>
        <Loader spinning={loading.effects['app/query']} />
        {children}
      </div>)
    }
    return (
      <LocaleProvider locale={zh_CN}>
        <div>
          <Loader fullScreen spinning={loading.effects['app/query']} />
          <Helmet>
            <title>易采通</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link rel="icon" href={logo} type="image/x-icon" />
            {iconFontJS && <script src={iconFontJS} />}
            {iconFontCSS && <link rel="stylesheet" href={iconFontCSS} />}
          </Helmet>
          <div className={classnames(styles.layout, { [styles.fold]: isNavbar ? false : siderFold }, { [styles.withnavbar]: isNavbar })}>
            {!isNavbar ? <aside className={classnames(styles.sider, { [styles.light]: !darkTheme })}>
              <Sider {...siderProps} />
            </aside> : ''}
            <div className={styles.main}>
              <Header {...headerProps} />
              <div className={styles.scollArea}>
                <Bread {...breadProps} />
                <div className={styles.container}>
                  <div className={styles.content}>
                    {
                      children
                      // hasPermission ? children : <Error />
                    }
                  </div>
                </div>
              </div>
              <Footer />
            </div>
          </div>
        </div>
      </LocaleProvider>
    )
  }
}


//export default connect(({ app, loading }) => ({ app, loading }))(App)
export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App))